//
//  MusicPlayingViewController.m
//  MyMusic
//
//  Created by mac on 2019/4/12.
//  Copyright © 2019 YangYang. All rights reserved.
//

#import "MusicPlayingViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "AlbumModel.h"
#import <AVFoundation/AVFoundation.h>
#import "VideoPlayerViewController.h"
#import "DateTimePickerView.h"

@interface MusicPlayingViewController ()<VLCMediaPlayerDelegate, DateTimePickerViewDelegate>
@property (nonatomic, strong) VLCMediaPlayer *player;
@property (nonatomic, strong) VLCMedia *media;



@property (nonatomic, strong) AlbumModel *currentPlayingModel;



@property (nonatomic, strong) UISlider *progressView;
@property (nonatomic, strong) UILabel *currentPlayingTimeView;
@property (nonatomic, strong) UILabel *allTimeView;
@property (nonatomic, strong) UIButton *playingView;
@property (nonatomic, strong) UIButton *lastMusicAction;
@property (nonatomic, strong) UIButton *nextMusicAction;

@property (nonatomic, strong) UILabel *songTitleView;
@property (nonatomic, strong) UILabel *singerView;
@property (nonatomic, strong) UIButton *videoActionView;
@property (nonatomic, strong) UIButton *timingActionView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) DateTimePickerView *datePickerView;
@property (nonatomic, assign) BOOL isRuningTimer;

@property (nonatomic, strong) AlbumModel *albumModel;
@property (nonatomic, strong) UIImageView *bgImageView;
/** 是否是手动暂停 */
@property (nonatomic, assign) BOOL isManualPause;

@end

@implementation MusicPlayingViewController

static NSInteger TimeCount;

__strong static MusicPlayingViewController *singleViewController = nil;
+(MusicPlayingViewController *)sharedInstance
{
    static dispatch_once_t pred = 0;
    dispatch_once(&pred, ^{
        singleViewController = [[super allocWithZone:NULL] init];
    });
    NSLog(@"singleViewController = %@",singleViewController);
    return singleViewController;
}

+(id)allocWithZone:(struct _NSZone *)zone
{
    return [self sharedInstance];
}

-(id)copyWithZone:(NSZone *)zone
{
    return self;
}

-(void)loadView
{
    [super loadView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(0xDAC5AC);
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    _isManualPause = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];
    
    
    [self initUI];
}

- (void)audioSessionInterruptionNotification:(NSNotification *)notification{
    NSInteger type = [notification.userInfo[AVAudioSessionInterruptionOptionKey] integerValue];
    switch (type) {
        case AVAudioSessionInterruptionTypeBegan:
        {//播放被中断
            GGLog(@"播放被中断");
            [self.player pause];
        }
            break;
        case AVAudioSessionInterruptionTypeEnded:
        {//中断结束
            GGLog(@"中断结束");
            [self.player play];
        }
            break;
            
        default:
            break;
    }
}

-(void)play:(AlbumModel *)model;
{
    NSLog(@"model = %@",model);
    NSLog(@"_currentPlayingModel = %@",_currentPlayingModel);
    
    if (model == _currentPlayingModel) {
        NSLog(@"正在播放点击的歌曲，继续播放");
    }
    else
    {
        NSLog(@"正在播放的歌曲与点击的歌曲不符，播放新音乐");
        _currentPlayingModel = model;
        [self playModel:_currentPlayingModel];
    }
}
#pragma mark -------- 播放MV ----------
-(void)playVideoAction
{
    if (_currentPlayingModel.videoURL.length > 0) {
        [self.player pause];
        VideoPlayerViewController *videoPlayerVC = [[VideoPlayerViewController alloc] init];
        videoPlayerVC.navigationItem.title = @"视频";
        videoPlayerVC.videoURL = _currentPlayingModel.videoURL;
        BackItemView
        [self.navigationController pushViewController:videoPlayerVC animated:YES];
    }
    
}

-(void)returnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -------- 展示倒计时 ----------
-(void)timerAction
{
    [self.datePickerView showDateTimePickerView];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
    NSString *startTimeStr = @"2019-04-21 00:00:00";
    NSDate *date = [formatter dateFromString:startTimeStr];
    self.datePickerView.currentDate = date;
}

-(void)initUI
{
    _bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:_bgImageView];
    _bgImageView.contentMode = UIViewContentModeScaleAspectFit;
    _bgImageView.image = [UIImage imageNamed:_currentPlayingModel.singerImage];
    
    UIView *topBgView = [[UIView alloc] init];
    [self.view addSubview:topBgView];
    topBgView.backgroundColor = [UIColor blackColor];
    topBgView.alpha = 0.2;
    [topBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).mas_offset(0);
        make.top.mas_equalTo(self.view.mas_top).mas_offset(0);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(100);
    }];
    
    UIButton *returnActionView = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:returnActionView];
    [returnActionView addTarget:self action:@selector(returnAction) forControlEvents:UIControlEventTouchUpInside];
    [returnActionView setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [returnActionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(topBgView.mas_left).mas_offset(10);
        make.top.mas_equalTo(topBgView.mas_top).mas_offset(20);
    }];
    
    _songTitleView = [[UILabel alloc] init];
    [self.view addSubview:_songTitleView];
    _songTitleView.font = [UIFont systemFontOfSize:15];
    _songTitleView.textColor = [UIColor whiteColor];
    _songTitleView.text = self.navigationItem.title;
    [_songTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(topBgView.mas_centerX).mas_offset(0);
        make.top.mas_equalTo(topBgView.mas_top).mas_offset(20);
        make.width.mas_lessThanOrEqualTo(kScreenWidth - 100);
    }];
    
    _singerView = [[UILabel alloc] init];
    [self.view addSubview:_singerView];
    _singerView.font = [UIFont systemFontOfSize:10];
    _singerView.textColor = [UIColor whiteColor];
    _singerView.text = @"歌手";
    [_singerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(topBgView.mas_centerX).mas_offset(0);
        make.top.mas_equalTo(self.songTitleView.mas_bottom).mas_offset(10);
        make.width.mas_lessThanOrEqualTo(kScreenWidth - 100);
    }];
    
    _videoActionView = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_videoActionView];
    [_videoActionView setTitle:@"MV" forState:UIControlStateNormal];
    [_videoActionView addTarget:self action:@selector(playVideoAction) forControlEvents:UIControlEventTouchUpInside];
    _videoActionView.titleLabel.font = [UIFont systemFontOfSize:10];
    [_videoActionView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _videoActionView.layer.cornerRadius = 2;
    _videoActionView.layer.borderColor = [UIColor whiteColor].CGColor;
    _videoActionView.layer.borderWidth = 1;
    [_videoActionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(topBgView.mas_centerX).mas_offset(-5);
        make.top.mas_equalTo(self.singerView.mas_bottom).mas_offset(10);
        make.width.mas_equalTo(25);
        make.height.mas_equalTo(15);
    }];
    
    _timingActionView = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_timingActionView];
    [_timingActionView setTitle:@"定时" forState:UIControlStateNormal];
    [_timingActionView addTarget:self action:@selector(timerAction) forControlEvents:UIControlEventTouchUpInside];
    _timingActionView.titleLabel.font = [UIFont systemFontOfSize:10];
    [_timingActionView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _timingActionView.layer.cornerRadius = 2;
    _timingActionView.layer.borderColor = [UIColor whiteColor].CGColor;
    _timingActionView.layer.borderWidth = 1;
    [_timingActionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(topBgView.mas_centerX).mas_offset(5);
        make.top.mas_equalTo(self.singerView.mas_bottom).mas_offset(10);
        make.width.mas_equalTo(25);
        make.height.mas_equalTo(15);
    }];
    
    _currentPlayingTimeView = [[UILabel alloc] init];
    [self.view addSubview:_currentPlayingTimeView];
    _currentPlayingTimeView.textAlignment = NSTextAlignmentCenter;
    _currentPlayingTimeView.font = [UIFont systemFontOfSize:13];
    _currentPlayingTimeView.textColor = [UIColor blackColor];
    
    [_currentPlayingTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).mas_offset(10);
        make.bottom.mas_equalTo(self.view.mas_bottom).mas_offset(-100);
        make.width.mas_equalTo(40);
    }];
    
    _allTimeView = [[UILabel alloc] init];
    [self.view addSubview:_allTimeView];
    _allTimeView.textAlignment = NSTextAlignmentCenter;
    _allTimeView.font = [UIFont systemFontOfSize:13];
    _allTimeView.textColor = [UIColor blackColor];
    [_allTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).mas_offset(-10);
        make.centerY.mas_equalTo(self.currentPlayingTimeView.mas_centerY).mas_offset(0);
        make.width.mas_equalTo(40);
    }];
    
    
    _progressView = [[UISlider alloc] init];
    [self.view addSubview:_progressView];
    _progressView.minimumValue = 0;
    _progressView.maximumValue = 1;
    
    _progressView.tintColor = [UIColor orangeColor];
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.allTimeView.mas_left).mas_offset(-10);
        make.left.mas_equalTo(self.currentPlayingTimeView.mas_right).mas_offset(10);
        make.centerY.mas_equalTo(self.currentPlayingTimeView.mas_centerY).mas_offset(0);
    }];
    [_progressView addTarget:self action:@selector(sliderActionMethod:) forControlEvents:UIControlEventValueChanged];
    
    _playingView = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_playingView];
    [_playingView setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    [_playingView setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateSelected];
    [_playingView addTarget:self action:@selector(playingActionMethod) forControlEvents:UIControlEventTouchUpInside];
    [_playingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX).mas_offset(0);
        make.top.mas_equalTo(self.progressView.mas_bottom).mas_offset(5);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    
    _lastMusicAction = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_lastMusicAction];
    [_lastMusicAction setImage:[UIImage imageNamed:@"上一首"] forState:UIControlStateNormal];
    [_lastMusicAction addTarget:self action:@selector(lastMusicActionmethod) forControlEvents:UIControlEventTouchUpInside];
    [_lastMusicAction mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.progressView.mas_left).mas_offset(0);
        make.centerY.mas_equalTo(self.playingView.mas_centerY).mas_offset(0);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    
    _nextMusicAction = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_nextMusicAction];
    [_nextMusicAction setImage:[UIImage imageNamed:@"下一首"] forState:UIControlStateNormal];
    [_nextMusicAction addTarget:self action:@selector(nextMusicActionMethod) forControlEvents:UIControlEventTouchUpInside];
    [_nextMusicAction mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.progressView.mas_right).mas_offset(0);
        make.centerY.mas_equalTo(self.playingView.mas_centerY).mas_offset(0);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];
    
    _bgImageView.image = [UIImage imageNamed:@"0.jpg"];
}

-(void)createAlbumModel
{
    _albumModel = [[AlbumModel alloc] init];
    _albumModel.albumName = _currentPlayingModel.songName;
    _albumModel.singerName = _currentPlayingModel.singerName;
    _albumModel.songName = _currentPlayingModel.songName;
    _albumModel.albumImage = _currentPlayingModel.albumImage;
    _albumModel.singerImage = _currentPlayingModel.singerImage;
    _albumModel.allDuration = self.player.media.length.intValue;
    _albumModel.currentDuration = self.player.time.intValue;
    _albumModel.songPath = _currentPlayingModel.songPath;
    _albumModel.songExtensionName = _currentPlayingModel.songExtensionName;
    _albumModel.downloadFolderName = _currentPlayingModel.downloadFolderName;
    
    
    
    
    CATransition *transition = [CATransition animation];
    transition.duration = 2.0f;
//    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
    transition.type = kCATransitionFade;
    [_bgImageView.layer addAnimation:transition forKey:@"a"];
    if (_currentPlayingModel.singerName.length > 0) {
        _bgImageView.image = [UIImage imageNamed:_currentPlayingModel.singerImage];
    }
    else
    {
        _bgImageView.image = [UIImage imageNamed:@"0.jpg"];
    }
    
    
}
#pragma mark -------- 播放与暂停 ----------
-(void)playingActionMethod
{
    if (_currentPlayingModel) {
        _playingView.selected = !_playingView.selected;
        if (_playingView.selected) {
            NSLog(@"播放");
            [self.player play];
            _isManualPause = NO;
        }
        else
        {
            NSLog(@"暂停");
            [self.player pause];
            
            NSMutableDictionary *currentMusicDic = [NSMutableDictionary dictionaryWithContentsOfFile:CurrentPlayingMusicPath];
            CurrentPlayingMusicModel *model = [CurrentPlayingMusicModel mj_objectWithKeyValues:currentMusicDic];
            model.currentDuration = self.player.time.intValue;
            CGFloat progress = (self.player.time.intValue * 1.0) / self.player.media.length.intValue;
            model.progress = progress;
            NSDictionary *currentDic = [model mj_keyValues];
            if ([currentDic writeToFile:CurrentPlayingMusicPath atomically:YES]) {
                NSLog(@"当前正在播放的歌曲信息更新成功");
            }
            else
            {
                NSLog(@"当前正在播放的歌曲信息更新失败");
            }
        }
    }
    
}

//-(void)setSongMessage:(AlbumModel *)model andCurrentIndex:(NSInteger)index andSongList:(NSArray *)songList
//{
////    _currentPlayingModel = model;
//    _currentPlayIndex = index;
//    _playListModels = songList;
//    [self play:model];
//}
#pragma mark -------- 上一首 ----------
-(void)lastMusicActionmethod
{
    if (_currentPlayingModel) {
        if (_currentPlayIndex > 0) {
            _currentPlayIndex--;
            _currentPlayingModel = self.playListModels[_currentPlayIndex];
            [self playModel:_currentPlayingModel];
        }
    }
}
#pragma mark -------- 下一首 ----------
-(void)nextMusicActionMethod
{
    if (_currentPlayingModel) {
        _currentPlayIndex++;
        if (_currentPlayIndex < self.playListModels.count) {
            _currentPlayingModel = self.playListModels[_currentPlayIndex];
            
            
            [self playModel:_currentPlayingModel];
            
        }
    }
    
}

-(void)sliderActionMethod:(UISlider *)sender
{
    
    int targetIntvalue = (int)(sender.value * self.player.media.length.intValue);
    
    VLCTime *targetTime = [[VLCTime alloc] initWithInt:targetIntvalue];
    
    [self.player setTime:targetTime];
    
}

-(void)playingToLength:(int)length
{
    if (length > 0) {
        VLCTime *targetTime = [[VLCTime alloc] initWithInt:length];
        [self.player setTime:targetTime];
    }
}

#pragma mark ----锁屏时候的设置，效果需要在真机上才可以看到
- (void)updateLockedScreenMusic
{
    [self createAlbumModel];
    // 播放信息中心
    MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
    
    // 初始化播放信息
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    // 专辑名称
    info[MPMediaItemPropertyAlbumTitle] = self.albumModel.albumName;
    // 歌手
    info[MPMediaItemPropertyArtist] = self.albumModel.singerName;
    // 歌曲名称
    info[MPMediaItemPropertyTitle] = self.albumModel.songName;
    // 设置图片
    info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:self.albumModel.albumImage]];
    // 设置持续时间（歌曲的总时间）
    info[MPMediaItemPropertyPlaybackDuration] = @(self.albumModel.allDuration * 0.001);
    // 设置当前播放进度
    info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(self.albumModel.currentDuration * 0.001);
    
    // 切换播放信息
    center.nowPlayingInfo = info;
    
    // 远程控制事件 Remote Control Event
    // 加速计事件 Motion Event
    // 触摸事件 Touch Event
    
    // 开始监听远程控制事件
    // 成为第一响应者（必备条件）
    [self becomeFirstResponder];
    // 开始监控
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    NSLog(@"远程控制");
    //    event.type; // 事件类型
    //    event.subtype; // 事件的子类型
    //    UIEventSubtypeRemoteControlPlay                 = 100,
    //    UIEventSubtypeRemoteControlPause                = 101,
    //    UIEventSubtypeRemoteControlStop                 = 102,
    //    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
    //    UIEventSubtypeRemoteControlNextTrack            = 104,
    //    UIEventSubtypeRemoteControlPreviousTrack        = 105,
    //    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
    //    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
    //    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
    //    UIEventSubtypeRemoteControlEndSeekingForward    = 109,
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            NSLog(@"播放与暂停");
            [self playingActionMethod];
            break;
            
        case UIEventSubtypeRemoteControlNextTrack:
            NSLog(@"下一首");
            [self nextMusicActionMethod];
            break;
            
        case UIEventSubtypeRemoteControlPreviousTrack:
            NSLog(@"上一首");
            [self lastMusicActionmethod];
            
        default:
            break;
    }
}

#pragma mark ------------------- DateTimePickerViewDelegate -------------------
-(void)didClickFinishDateTimePickerView:(NSString *_Nullable)date;
{
    NSLog(@"date = %@",date);
    NSArray *dateArr = [date componentsSeparatedByString:@":"];
    NSLog(@"dateArr = %@",dateArr);
    
    NSInteger hour = [[dateArr firstObject] integerValue];
    NSInteger minute = [[dateArr lastObject] integerValue];
    TimeCount = hour * 60 * 60 + minute * 60;
    if (TimeCount > 0) {
        [self timerStartsTiming];
    }
}
#pragma mark -------- 创建计时器 ----------
-(void)timerStartsTiming
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerFunction:) userInfo:nil repeats:YES];
    }
    else
    {
        NSLog(@"已有计时器，无需重新创建");
    }
}
#pragma mark -------- 计时方法 ----------
-(void)timerFunction:(NSTimer *)timer
{
    NSLog(@"开始计时器");
    NSInteger hour = TimeCount / 60 / 60;
    NSInteger minute = TimeCount / 60 % 60;
    NSInteger second = TimeCount % 60;
    NSString *timeString = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld",hour,minute,second];
    [_timingActionView setTitle:timeString forState:UIControlStateNormal];
    if (!_isRuningTimer) {
        _isRuningTimer = YES;
        [_timingActionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(50);
        }];
    }
    
    NSLog(@"timeString = %@",timeString);
    TimeCount--;
    if (TimeCount <= 0) {
        NSLog(@"计时结束");
        if ([self.player isPlaying]) {
            [self playingActionMethod];
        }
        _isRuningTimer = NO;
        [_timer invalidate];
        _timer = nil;
        [_timingActionView setTitle:@"定时" forState:UIControlStateNormal];
        [_timingActionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(25);
        }];
    }
}
#pragma mark ------------------- VLCMediaPlayerDelegate -------------------
- (void)mediaPlayerStateChanged:(NSNotification *)aNotification
{
    NSLog(@"mediaPlayerStateChanged");
    [self updateLockedScreenMusic];
    id object = aNotification.object;
    if ([object isKindOfClass:[VLCMediaPlayer class]]) {
        VLCMediaPlayer *player = (VLCMediaPlayer *)object;
        if ([player isPlaying]) {
            _playingView.selected = YES;
        }
        else
        {
            _playingView.selected = NO;
        }
        
        PlayerBottomView *bottomView = [PlayerBottomView shareInstance];
        bottomView.isPlaying = _playingView.selected;
        
        
        
        
        
        NSLog(@"mediaPlayerStateChanged");
        NSLog(@"状态：%ld",(long)player.state);
        switch ((int)player.state) {
            case VLCMediaPlayerStateStopped: // 停止播放（播放完毕或手动stop）
            {
                NSLog(@"停止播放（播放完毕或手动stop）");
                
                if (_isManualPause) {
                    
                }
                else
                {
                    GGLog(@"因为某些原因导致播放为正常结束(失败)继续开始播放下一首");
                    _currentPlayIndex++;
                    if (_currentPlayIndex < self.playListModels.count) {
                        _currentPlayingModel = self.playListModels[_currentPlayIndex];
                        
                        [self playModel:_currentPlayingModel];
                    }
                    
                }
            }
                break;
            case VLCMediaPlayerStateBuffering: // 播放中缓冲状态
            {
                // 显示菊花
                NSLog(@"播放中缓冲状态");
            }
                break;
            case VLCMediaPlayerStatePlaying: // 被暂停后开始播放
            {
                NSLog(@"被暂停后开始播放");
            }
                break;
            case VLCMediaPlayerStatePaused:  // 播放后被暂停
            {
                NSLog(@"播放后被暂停");
            }
                break;
                
        }
        
        
        
        
        
        
    }
}

- (void)mediaPlayerTimeChanged:(NSNotification *)aNotification
{
    
    id object = aNotification.object;
    if ([object isKindOfClass:[VLCMediaPlayer class]]) {
        VLCMediaPlayer *currentPlayer = (VLCMediaPlayer *)object;
        
        _currentPlayingTimeView.text = currentPlayer.time.stringValue;
        _allTimeView.text = currentPlayer.media.length.stringValue;
        CGFloat progress = (currentPlayer.time.intValue * 1.0) / currentPlayer.media.length.intValue;
        _progressView.value = progress;
        
        PlayerBottomView *bottomView = [PlayerBottomView shareInstance];
        bottomView.progress = progress;
        
        if (progress == 1 || [_currentPlayingTimeView.text isEqualToString:_allTimeView.text]) {
            if (_currentPlayIndex < self.playListModels.count) {
                
                
                _currentPlayIndex++;
                _currentPlayingModel = self.playListModels[_currentPlayIndex];
                
                [self playModel:_currentPlayingModel];
            }
            else
            {
                [self.player stop];
                _isManualPause = YES;
            }
            
        }
    }
}


- (void)mediaPlayerStartedRecording:(VLCMediaPlayer *)player
{
    NSLog(@"mediaPlayerStartedRecording");
}

-(void)playModel:(AlbumModel *)model
{
//    self.navigationItem.title = model.songName;
    self.songTitleView.text = model.songName;
    PlayerBottomView *bottomView = [PlayerBottomView shareInstance];
    bottomView.model = model;
    
    CurrentPlayingMusicModel *currentPlayingModel = [CurrentPlayingMusicModel new];
    
    currentPlayingModel.playingIndex = _currentPlayIndex;
    NSArray *playList = [AlbumModel mj_keyValuesArrayWithObjectArray:_playListModels];
    currentPlayingModel.playingList = playList;
    
    NSDictionary *currentPlayingDic = [currentPlayingModel mj_keyValues];
    NSLog(@"currentPlayingDic = %@",currentPlayingDic);
    if ([currentPlayingDic writeToFile:CurrentPlayingMusicPath atomically:YES]) {
        NSLog(@"将当前正在播放的歌曲信息写入成功");
    }
    else
    {
        NSLog(@"将当前正在播放的歌曲信息写入失败");
    }
    
    switch (_currentPlayingModel.type) {
        case WorksSourceTypeLocal:
        {
            _media = [VLCMedia mediaWithPath:_currentPlayingModel.songPath];
        }
            break;
        case WorksSourceTypeNet:
        {
            
            NSString *path = _currentPlayingModel.songPath;
            NSString *fileName = [path lastPathComponent];
            NSString *localMusicPath = [NSString stringWithFormat:@"%@/%@",DownloadFilePath(_currentPlayingModel.downloadFolderName),fileName];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL isDir = NO;
            if ([fileManager fileExistsAtPath:localMusicPath isDirectory:&isDir]) {
                NSLog(@"文件已被下载下来，播放本地文件");
                NSURL *musicURL = [NSURL fileURLWithPath:localMusicPath];
                _media = [VLCMedia mediaWithURL:musicURL];
            }
            else
            {
                NSString *musicURL = [_currentPlayingModel.songPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                _media = [VLCMedia mediaWithURL:[NSURL URLWithString:musicURL]];
            }
        }
            break;
            
        default:
            break;
    }
    
    self.player.media = _media;
    [self.player play];
    _isManualPause = NO;
}
#pragma mark -------- 是否正在播放 ----------
-(BOOL)isPlaying
{
    return _playingView.selected;
}

-(VLCMediaPlayer *)player
{
    if (!_player) {
        _player = [[VLCMediaPlayer alloc] init];
        _player.delegate = self;
    }
    return _player;
}

-(DateTimePickerView *)datePickerView
{
    if (!_datePickerView) {
        _datePickerView = [[DateTimePickerView alloc] init];
        _datePickerView.delegate = self;
        _datePickerView.pickerViewMode = DatePickerViewTimeMode;
        [self.view addSubview:_datePickerView];
    }
    return _datePickerView;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"视图即将出现");
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"视图已经出现");
    PlayerBottomView *bottomView = [PlayerBottomView shareInstance];
    [UIView animateWithDuration:0.5f animations:^{
        bottomView.frame = CGRectMake(0, kScreenHeight + 10, kScreenWidth, CGRectGetHeight(bottomView.frame));
    } completion:^(BOOL finished) {
//        bottomView.hidden = YES;
    }];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSLog(@"视图即将消失");
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSLog(@"视图已经消失");
    PlayerBottomView *bottomView = [PlayerBottomView shareInstance];
    [UIView animateWithDuration:0.5f animations:^{
        bottomView.frame = CGRectMake(0, kScreenHeight - CGRectGetHeight(bottomView.frame), kScreenWidth, CGRectGetHeight(bottomView.frame));
    } completion:^(BOOL finished) {
//        bottomView.hidden = NO;
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
